package com.nbufe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nbufe.domain.ResponseResult;
import com.nbufe.domain.dto.QueryElectricHeatDTO;
import com.nbufe.domain.dto.QueryFixCarbonDTO;
import com.nbufe.domain.entity.ElectricHeat;
import com.nbufe.domain.entity.EmissionOrigin;
import com.nbufe.domain.entity.FixCarbon;
import com.nbufe.domain.entity.Material;
import com.nbufe.domain.entity.Process;
import com.nbufe.domain.form.AddFixCarbonInfoForm;
import com.nbufe.domain.form.ModifyFixCarbonForm;
import com.nbufe.domain.form.QueryFixCarbonForm;
import com.nbufe.domain.vo.PageVo;
import com.nbufe.mapper.FixCarbonMapper;
import com.nbufe.mapper.MaterialMapper;
import com.nbufe.mapper.ProcessMapper;
import com.nbufe.service.DataService;
import com.nbufe.service.FixCarbonService;
import com.nbufe.utils.BeanCopyUtils;
import com.nbufe.utils.HttpContextUtils;
import com.nbufe.utils.UnderUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * (FixCarbon)表服务实现类
 *
 * @author luzhiheng
 * @since 2023-04-01 10:10:32
 */
@Service("fixCarbonService")
public class FixCarbonServiceImpl extends ServiceImpl<FixCarbonMapper, FixCarbon> implements FixCarbonService {

    @Resource
    private DataService dataService;

    @Resource
    private MaterialMapper materialMapper;

    @Resource
    private ProcessMapper processMapper;

    @Override
    public ResponseResult pageList(QueryFixCarbonForm form) {
        Page<FixCarbon> page = new Page<>(form.getPageNum(), form.getPageSize());
        QueryWrapper<FixCarbon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Objects.nonNull(form.getFixCarbonId()), "fix_carbon_id", form.getFixCarbonId());
        queryWrapper.eq(Objects.nonNull(form.getYear()), "year", form.getYear());
        queryWrapper.eq(Objects.nonNull(form.getMonth()), "month", form.getMonth());
        String tenantId = HttpContextUtils.getRequest().getHeader("tenant-id");
        queryWrapper.eq("tenant_id", Long.valueOf(tenantId));

        List<Map<String, String>> sortArr = form.getSortArr();
        if (sortArr.size() > 0) {
            for (Map<String, String> map : sortArr) {
                String order = map.get("order");
                String prop = map.get("prop");
                prop = UnderUtil.camel2under(prop);
                if ("ascending".equals(order)) {
                    queryWrapper.orderByAsc(prop);
                } else if ("descending".equals(order)) {
                    queryWrapper.orderByDesc(prop);
                }
            }
        }

        page(page, queryWrapper);

        Map<Long, List<EmissionOrigin>> map = dataService.queryTargetStageEmissionOrigin(4).stream().collect(Collectors.groupingBy(EmissionOrigin::getId));

        List<FixCarbon> fixCarbonList = page.getRecords();
        List<QueryFixCarbonDTO> queryFixCarbonDto = BeanCopyUtils.copyBeanList(fixCarbonList, QueryFixCarbonDTO.class);
        //封装电力热力名称
        queryFixCarbonDto = queryFixCarbonDto.stream()
                .peek(dto -> {
                    Process process = processMapper.selectById(dto.getProcessId());
                    dto.setProcessName(process != null ? process.getName() : "");
                    Long fixCarbonId = dto.getFixCarbonId();
                    dto.setName(map.get(fixCarbonId).get(0).getName());
                }).collect(Collectors.toList());
        PageVo pageVo = new PageVo(page.getTotal(), queryFixCarbonDto);
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public List<Integer> listYears() {
        return baseMapper.selectAllYears();
    }

    @Override
    public List<Material> listAllFixCarbon() {
        List<Material> materialList = materialMapper.selectList(
                new LambdaQueryWrapper<Material>().eq(Material::getProduceStage, 4)
        );
        return materialList;
    }

    @Override
    public ResponseResult modifyFixCarbonInfo(ModifyFixCarbonForm form) {
        FixCarbon fixCarbon = BeanCopyUtils.copyBean(form, FixCarbon.class);
        BigDecimal production = BigDecimal.valueOf(fixCarbon.getProduction());
        BigDecimal emissionFactor = BigDecimal.valueOf(fixCarbon.getEmissionFactor());
        double carbonEmission = production.multiply(emissionFactor).setScale(2, RoundingMode.UP).doubleValue();
        fixCarbon.setCarbonEmission(carbonEmission);
        updateById(fixCarbon);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult deleteOneOrBatch(List<Integer> ids) {
        removeBatchByIds(ids);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult addFixCarbonInfo(AddFixCarbonInfoForm form) {
        FixCarbon fixCarbon = BeanCopyUtils.copyBean(form, FixCarbon.class);
        fixCarbon.setCarbonEmission(
                BigDecimal.valueOf(form.getProduction())
                        .multiply(BigDecimal.valueOf(form.getEmissionFactor()))
                        .setScale(2, RoundingMode.UP).doubleValue()
        );
        save(fixCarbon);
        return ResponseResult.okResult();
    }
}